<template>
  <!-- 供应商分类 -->
  <MainSlot>
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" @search="(e) => {
          (searchlist = { ...e }), (currentPage = 1), getTableDataList();
        }
        ">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <TableData :isSelect="true" :tableThead="tableThead" :dataList="dataList" :config="table_config"
        @selection-change="selectionChange">
        <template v-slot:isFreecust="{ row }">
          <span>{{ row.isFreecust ? "是" : "否" }}</span>
        </template>
        <template v-slot:enableStatus="{ row }">
          <span>{{ row.enableStatus ? "是" : "否" }}</span>
        </template>
      </TableData>
    </template>
    <template v-slot:pagination>
      <Pagination @size-Change="changePageSize" :size="pageSize" @current-change="handleCurrentChange"
        :page="currentPage" :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <el-dialog :close-on-click-modal="false" :title="dialogTitle + '供应商信息'" :visible.sync="dialogFormVisible"
        :before-close="cancel">
        <FormYy ref="formData" :labelWidth="'150px'" :formData="formData" :formConfig="formlist" :rules="rules">
        </FormYy>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button class="zh-button-two" type="primary" @click="save('formData')">保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components/MainSlot";
import Pagination from "@/components/Pagination";
import SearchForm from "@/components/SearchForm";
import TableData from "@/components/TableData";
import BtnSlot from "@/components/BtnSlot";

import FormYy from "@/components_yy/searchForm/formlist";
import supplierApi from "@/api/digtalOperation/purchase-manage/supplier";
import supplierTypeApi from "@/api/digtalOperation/purchase-manage/supplier-type";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";
import { log } from "three";
export default {
  name: "AgrInputManagementtwo",
  components: { SearchForm, TableData, BtnSlot, Pagination, MainSlot, FormYy },
  mixins: [mymixin],
  data() {
    return {
      SupplierTypeList: [], //供应商类型名称
      total: 100,
      selectIndex: 0,
      currentPage: 1,
      dataList: [],
      selectionList: [],
      formItemList: [
        {
          label: "供应商名称",
          type: "input",
          param: "supplierName",
          isShow: true,
        },
        {
          selectOptions: [],
          label: "供应商类型",
          type: "select",
          param: "supplierTypeNo",
          defaultSelect: "",
          multiple: false,
          isShow: true,
        },
        {
          label: "供应商简称",
          param: "shortName",
          isShow: true,
          type: "input",
        },
        {
          label: "社会信用代码",
          param: "creditCode",
          isShow: true,
          type: "input",
        },
        {
          label: "所属行业",
          param: "trade",
          isShow: true,
          type: "input",
        },
      ],
      btnList: ["add", "delete"],
      rules: {},
      formData: {},
      tableThead: [
        // { isShow: true, label: "供应商名称", prop: "supplierName" },
        // { isShow: true, label: "供应商简称", prop: "shortName" },
        // { isShow: true, label: "供应商类型", prop: "supplierTypeNo" },
        // { isShow: true, label: "统一社会信用代码", prop: "creditCode" },
        // { isShow: true, label: "所属行业", prop: "trade" },
        // { isShow: true, label: "散户", prop: "isFreecust" },
        // { isShow: true, label: "法人", prop: "legalBody" },
        // { isShow: true, label: "企业地址", prop: "address" },
        // { isShow: true, label: "电话", prop: "tel" },
        // { isShow: true, label: "Web网址", prop: "url" },
        // { isShow: true, label: "e-mail地址", prop: "email" },
        // { isShow: true, label: "国家/地区", prop: "country" },
        // { isShow: true, label: "开户行", prop: "bank" },
        // { isShow: true, label: "银行帐号", prop: "bankAccount" },
        // { isShow: true, label: "是否启用", prop: "enableStatus" },
        // { isShow: true, label: "备注", prop: "remarks" },
      ],
      // 配置项
      table_config: {
        isCheckBox: true,
        isOperation: true,
        // 表格操作列
        operation: {
          label: "操作",
          width: "150",
          cols: [
            {
              label: "编辑",
              type: "primary",
              flag: "edit",
              handleRow: this.handleRow,
            },
            {
              label: "删除",
              type: "danger",
              flag: "delete",
              handleRow: this.handleRow,
            },
          ],
        },
      },

      formlist: [
        {
          label: "供应商名称",
          prop: "supplierName",
          type: "input",
          required: true,
        },
        {
          label: "供应商简称",
          prop: "shortName",
          type: "input",
        },
        {
          label: "供应商类型",
          prop: "supplierTypeNo",
          type: "select",
          options: [],
          // required: true
        },
        {
          label: "统一社会信用代码",
          prop: "creditCode",
          type: "input",
          // required: true
        },
        {
          label: "所属行业",
          prop: "trade",
          type: "input",
          // required: true
        },
        {
          label: "散户",
          prop: "isFreecust",
          type: "select",
          options: [
            { label: "是", value: true },
            { label: "否", value: false },
          ],
          optionKey: { label: "label", value: "value" },
          required: true,
        },
        {
          label: "法人",
          prop: "legalBody",
          type: "input",
          // required: true
        },
        {
          type: "input",
          prop: "address",
          label: "企业地址",
        },
        {
          type: "input",
          prop: "tel",
          label: "电话",
          // required: true
        },
        {
          type: "input",
          prop: "url",
          label: "Web网址",
        },
        {
          type: "input",
          prop: "email",
          label: "e-mail地址",
        },
        {
          type: "input",
          prop: "country",
          label: "国家/地区",
          // required: true
        },
        {
          type: "input",
          prop: "bank",
          label: "开户行",
          // required: true
        },
        {
          type: "input",
          prop: "bankAccount",
          label: "银行帐号",
          // required: true
        },
        {
          type: "select",
          prop: "enableStatus",
          label: "是否启用",
          options: [
            { label: "是", value: true },
            { label: "否", value: false },
          ],
          optionKey: { label: "label", value: "value" },
          required: true,
        },
        {
          type: "input",
          prop: "remarks",
          label: "备注",
        },
      ],
      // =====================下面可能是用不上的，但是不敢删
      tableColumn: [
        { prop: "supplierTypeName", label: "供应商类型名称" },
        { prop: "remarks", label: "备注" },
        {
          prop: "operation",
          label: "操作",
          slotName: "operation",
          width: "120",
        },
      ],
      searchlist: {},
      formConfig: [
        {
          label: "供应商类型名称",
          prop: "supplierTypeName",
          type: "input",
        },
      ],
      dialogTitle: null,
      dialogFormVisible: false,
    };
  },
  created() {
    let list = [];
    this.formlist.forEach((el) => {
      let obj = {
        isShow: true,
        label: el.label,
      };
      if (el.prop == "isFreecust" || el.prop == "enableStatus") {
        obj.slotName = el.prop;
      } else if (el.prop == "supplierTypeNo") {
        obj.prop = 'supplierTypeName';
      } else {
        obj.prop = el.prop;
      }
      list.push(obj);
    });
    this.tableThead = list;
    console.log(list);
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission",
    }),
  },
  watch: {},
  mounted() {
    this.getTableDataList();
    this.getSupplierTypeList();
  },
  methods: {
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = [];
      list.forEach((item, index) => {
        if (item.param == "supplierTypeNo") {
          let selectOptions = this.SupplierTypeList.map((data) => {
            return {
              text: data.supplierTypeName,
              value: data.supplierTypeNo,
            };
          });
          item.selectOptions = selectOptions;
        }
      });
      this.$nextTick(() => {
        this.$set(this, "formItemList", list);
      });
      console.log(this.formItemList);
    },
    async getSupplierTypeList() {
      let res = await supplierTypeApi.conditionQuery({});
      console.log(res, '1111111111111111111111111111111111111');
      if (res.code === 1) {
        let list = [];
        this.SupplierTypeList = res.data;
        // 提供表头搜索数据
        res.data.forEach((item) => {
          list.push({
            label: item.supplierTypeName,
            value: item.supplierTypeNo,
          });
        });
        this.setFormOptions();
        this.setOptions(this.formConfig, "supplierTypeNo", list);
        this.setOptions(this.formlist, "supplierTypeNo", list);
      }
    },
    // 多选方法
    selectionChange(val) {
      this.selectionList = val || [];
    },
    handleCurrentChange(val) {
      console.log(val);
      this.currentPage = val;
      this.getTableDataList();
    },
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag);
      if (flag == "add") {
        this.add();
      } else if (flag == "delete") {
        if (this.selectionList.length > 0) {
          this.handleDelete(this.selectionList);
        } else {
          this.$message.warning("请先选择表单数据项后再删除！");
        }
      }
      this.addEditFlag = flag;
    },
    add() {
      this.formData = {};
      this.openDialog("add");
    },
    cancel() {
      this.closeDialog();
      this.formData = {};
    },
    openDialog(type) {
      console.log(type);
      this.dialogFormVisible = true;
      this.dialogTitle = type === "add" ? "新增" : "编辑";
      this.nowChanceStau = type;
    },
    closeDialog() {
      this.dialogFormVisible = false;
      this.dialogFormAssignVisible = false;
      this.dialogTitle = null;
      this.nowChanceStau = "";
    },
    // 操作方法
    handleRow(rowData, item) {
      if (item.flag == "edit") {
        this.dialogFormVisible = true;
        this.dialogTitle = item.flag === "add" ? "新增" : "编辑";
        this.nowChanceStau = "edit";
        this.formData = JSON.parse(JSON.stringify(rowData));
      } else if (item.flag == "delete") {
        this.handleDelete([rowData]);
      }
      this.addEditFlag = item.flag;
    },
    // 获取当前表格信息
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        // sortList: this.sortList || [],
        entity: {
          ...this.searchlist,
          organizationNo: sessionStorage.organizationNo,
        },
      };
      this.entity = params.entity;
      supplierApi.pageQuery(params).then((res) => {
        this.loading = false;
        if (res.code !== 1) {
          this.$message.error(res.msg);
          return;
        }
        let data = res.data;
        this.dataList = data.content || [];
        this.total = data.totalElements;
      });
    },

    search() {
      this.currentPage = 1;
      this.setFormOptions();
      this.getTableDataList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableDataList();
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableDataList();
    },

    // 表格点击
    handleEdit(list) {
      this.formData = { ...list };
      this.openDialog("edit");
    },
    handleSelectionChange(list) {
      this.selectIdList = [];
      this.selectIdList = list.map((item) => {
        return item.supplierNo;
      });
    },

    handleDelete(list) {
      let selectedStaffList = [];
      list.forEach((item) => {
        selectedStaffList.push(item.supplierNo);
      });
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(() => {
          let params = {
            noList: selectedStaffList,
          };
          supplierApi.numberBatchDel(params).then((res) => {
            if (res.code === 1) {
              this.$message.success("删除成功");
              this.getTableDataList();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    save(formData) {
      let ruleForm = this.$refs[formData]?.$refs.ruleForm;
      ruleForm?.validate((valid) => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            supplierApi.edit(this.formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                ruleForm.resetFields();
                this.closeDialog();
                this.getTableDataList();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            supplierApi.add(this.formData).then((res) => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                ruleForm.resetFields();
                this.closeDialog();
                this.getTableDataList();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.tabhid {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  // background-color: #0cb28c;
}

.zhtabletitle {
  color: #31f7dd;
  margin-bottom: 10px;
}

::v-deep .staff-manage .common-layout .content {
  overflow-y: auto;
}

.upimg {
  ::v-deep .xunzeimage {
    width: 140px !important;
  }
}

.dialog {
  img {
    width: auto;
    max-width: 100%;
  }
}

::v-deep .el-upload--picture-card {
  width: 40px;
  height: 40px;
  background-color: rgba(255, 255, 255, 0.1);
  border: 1px solid #6ecae3;
}

::v-deep .el-upload--picture-card {
  position: relative;
}

::v-deep .el-upload--picture-card .el-icon-plus {
  font-size: 34px;
  color: #6ecae3;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

::v-deep .el-dialog__body {
  height: 90%;
  // img {
  //   width: 100%;
  // }
}

::v-deep .el-upload__tip {
  display: none;
}

::v-deep .el-form {
  display: flex;
  //   .el-form-item__label {
  //     min-width: 130px !important;
  //   }
}
</style>
